
圖片來源:Threads
可能會交換靈魂也說不...呀哈。
本篇紀錄不可思議事件:copy事件。
此事件發生於人類複刻元素之內容之時,通常為鼠輩點按元素某處後拖曳選取元素並釋放,或按壓鍵石ctrl與C時得複刻元素之內容。
規範原文:
When the user initiates a copy action, the user agent fires a clipboard event named copy.
複刻之內容可操以文件之術法getSelection()取得,然此術回傳之物為一Selection物件,若要取得內容之文字,可以toString()之術取得。
以下示例將製一簡易今日運勢抽籤器。
const textForCopy = document.querySelector(".text-copy");
const todaysFortune = document.querySelector(".fortune-today");
function drawFortune(event) {
  const selectionText = document.getSelection().toString();
    
  // 機密內容
}
textForCopy.addEventListener("copy", drawFortune);
分段註釋如下:
選取文字元素與今日運勢元素。
const textForCopy = document.querySelector(".text-copy");
const todaysFortune = document.querySelector(".fortune-today");
定義函式之術drawFortune,內容為操以文件之術法getSelection()與toString()之術取得選取之文字後,施以機密函式內容以取得今日運勢元素之內容。
function drawFortune(event) {
  const selectionText = document.getSelection().toString();
    
  // 機密內容
  todaysFortune.textContent = "???";
  // 機密內容
}
於文字元素設定copy事件之觀測器,於使用者複刻文字元素之時施以drawFortune函式之術。
textForCopy.addEventListener("copy", drawFortune);
鼠輩選取文字元素後同時按壓鍵石ctrl與C,即可顯示本日運勢。
看來紀錄者今日運勢不佳。
Selection物件Selection物件內含名帶anchor之屬性及名帶focus之屬性,前者表使用者選取之起始,後者表使用者選取之終末。
MDN:
The anchor is where the user began the selection and the focus is where the user ends the selection.
下圖為使用者由左至右選取第一字「複」。
則Selection物件內之anchorOffset屬性值為0,表起始之處為第一字符前方,而focusOffset屬性值為1,表終末之處為第二字符前方。
https://github.com/CReticulata/2024ithome/tree/main/Day28
鼠輩:滑鼠
鍵石:鍵盤按鍵
複刻:複製
文件:document